package com.andy.blog.quartz.util;

import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.constant.ScheduleConstants;
import com.andy.blog.common.utils.DateUtils;
import com.andy.blog.common.utils.ExceptionUtil;
import com.andy.blog.common.utils.StringUtils;
import com.andy.blog.common.utils.bean.BeanUtils;
import com.andy.blog.common.utils.spring.SpringBeanUtils;
import com.andy.blog.dal.vo.SysJobLogVO;
import com.andy.blog.quartz.dto.SysJob;
import com.andy.blog.quartz.service.SysJobLogBusService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 抽象quartz调用
 * Created by andy on 2023-04-05 11:38
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static final ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        SysJob sysJob = new SysJob();
        BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
        try {
            before(context, sysJob);
            if (sysJob != null) {
                doExecute(context, sysJob);
            }
            after(sysJob, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     */
    protected void before(JobExecutionContext context, SysJob sysJob) {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param sysJob  系统计划任务
     */
    protected void after(SysJob sysJob, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        final SysJobLogVO sysJobLog = new SysJobLogVO();
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());

        long runMs = DateUtils.getCurrentDate().getTime() - startTime.getTime();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "ms");
        if (e != null) {
            sysJobLog.setStatus(BaseConstants.FAIL);
            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus(BaseConstants.SUCCESS);
        }

        sysJobLog.setCreateTime(DateUtils.getCurrentDate());

        // 写入数据库当中
        SpringBeanUtils.getBean(SysJobLogBusService.class).addJobLog(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
